package pswvclass.pswvandroid2.com.kwords;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import pswvclass.pswvandroid2.R;
import pswvclass.pswvandroid2.com.Home;
import pswvclass.pswvandroid2.com.kwords.share.ShareDisplay;
import pswvclass.pswvandroid2.com.kwords.share.ShareMyDisplay;
import pswvclass.pswvandroid2.com.util.DBHelper;
import pswvclass.pswvandroid2.com.util.HandleBackUtil;
import pswvclass.pswvandroid2.com.util.HttpUtils;
import pswvclass.pswvandroid2.com.util.HandleBackInterface;

/**
 * Created by Administrator on 2018/11/2.
 */

/**
 * 长按菜单响应函数
 */
public class KwordList extends Fragment implements View.OnClickListener {
    private String tag = "KwordList";
    private Button kword_add;
    private Button kword_search;
    private Button kword_search_share;
    private Button display_all;
    private Button display_all_share;
    private Button my_share;
    private TextView text_search;
    protected static final int SEE_MY_SHARE = 6;
    protected static final int SHARE_SUCCESS = 5;
    protected static final int SHARESEARCH_SUCCESS = 4;
    protected static final int KWORDSEARCH_SUCCESS = 3;
    protected static final int NO_ADD = 2;
    protected static final int ERROR = 1;
    protected static final int SUCCESS = 0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.pswv_kword_list, null);

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        text_search = (TextView) getView().findViewById(R.id.text_search);
        kword_add = (Button) getView().findViewById(R.id.kword_add);
        kword_add.setOnClickListener(this);
        display_all = (Button) getView().findViewById(R.id.display_all);
        display_all.setOnClickListener(this);
        kword_search = (Button) getView().findViewById(R.id.kword_search);
        kword_search.setOnClickListener(this);
        display_all_share = (Button) getView().findViewById(R.id.display_all_share);
        display_all_share.setOnClickListener(this);
        kword_search_share = (Button) getView().findViewById(R.id.kword_search_share);
        kword_search_share.setOnClickListener(this);
        my_share = (Button) getView().findViewById(R.id.my_share);
        my_share.setOnClickListener(this);

    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SEE_MY_SHARE:
                    try {
                        JSONArray data = (JSONArray) msg.obj;
                        ShareMyDisplay smd = new ShareMyDisplay();
                        Bundle bundle = new Bundle();
                        bundle.putString("data", data + "");
                        smd.setArguments(bundle);
                        getFragmentManager()
                                .beginTransaction()
                                .addToBackStack(null)
                                .replace(R.id.realtabcontent, smd).commit();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                case SUCCESS:
                    try {
                        JSONArray data = (JSONArray) msg.obj;
                        KwordDisplay kd = new KwordDisplay();
                        Bundle bundle = new Bundle();
                        bundle.putString("data", data + "");
                        kd.setArguments(bundle);
                        getFragmentManager()
                                .beginTransaction()
                                .addToBackStack(null)
                                .replace(R.id.realtabcontent, kd).commit();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                case SHARE_SUCCESS:
                    try {
                        JSONArray data = (JSONArray) msg.obj;
                        ShareDisplay sd = new ShareDisplay();
                        Bundle bundle = new Bundle();
                        bundle.putString("data", data + "");
                        sd.setArguments(bundle);
                        getFragmentManager()
                                .beginTransaction()
                                .addToBackStack(null)
                                .replace(R.id.realtabcontent, sd).commit();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                case KWORDSEARCH_SUCCESS:
                    try {
                        JSONArray data = (JSONArray) msg.obj;
                        KwordDisplay kd = new KwordDisplay();
                        Bundle bundle = new Bundle();
                        bundle.putString("data", data + "");
                        kd.setArguments(bundle);
                        getFragmentManager()
                                .beginTransaction()
                                .addToBackStack(null)
                                .replace(R.id.realtabcontent, kd).commit();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                case SHARESEARCH_SUCCESS:
                    try {
                        JSONArray data = (JSONArray) msg.obj;
                        ShareDisplay sd = new ShareDisplay();
                        Bundle bundle = new Bundle();
                        bundle.putString("data", data + "");
                        sd.setArguments(bundle);
                        getFragmentManager()
                                .beginTransaction()
                                .addToBackStack(null)
                                .replace(R.id.realtabcontent, sd).commit();
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    break;
                case ERROR:
                    Toast.makeText(getContext(), "连接错误 ....", Toast.LENGTH_SHORT).show();
                    break;
                case NO_ADD:
                    Toast.makeText(getContext(), " 没有查询到....", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.my_share: {
                DBHelper db = new DBHelper(getContext());
                SQLiteDatabase sd = db.getWritableDatabase();
                int userId = 0;
                Cursor cursor = sd.query("user", new String[]{"userId"}, "state=?", new String[]{"1"}, null, null, null);
                while (cursor.moveToNext()) {
                    userId = cursor.getInt(0);
                }
                cursor.close();
                final int finalUserId = userId;
                new Thread() {
                    public void run() {
                        try {
                            HttpUtils hu = new HttpUtils();
                            String data2;
                            final String src = getResources().getString(R.string.src_mysql) + "pswv/api/shareKWordAction/queryUserMyShareKWord";
                            final Map<String, String> map1 = new HashMap<String, String>();
                            map1.put("userId", finalUserId + "");
                            data2 = hu.submitPostData(src, map1, "utf-8");
                            JSONObject jsonObj = new JSONObject(data2);
                            Log.v(tag, jsonObj + "");
                            int result = Integer.parseInt(jsonObj.getString("code"));
                            JSONObject jsonObj1 = jsonObj.getJSONObject("response");
                            JSONArray jsonArray = jsonObj1.getJSONArray("list");
                            if (result == 0) {
                                Message msg = Message.obtain();
                                msg.what = SEE_MY_SHARE;
                                msg.obj = jsonArray;
                                mHandler.sendMessage(msg);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Message msg = Message.obtain();
                            msg.what = ERROR;
                            mHandler.sendMessage(msg);
                        }
                    }
                }.start();
            }
            break;
            case R.id.kword_add: {

                getFragmentManager()
                        .beginTransaction()
                        .addToBackStack(null)
                        .replace(R.id.realtabcontent, new KwordAdd()).commit();
                //  startActivity(new Intent(getContext(), RiskAdd.class));
                break;
            }
            case R.id.display_all: {
                DBHelper db = new DBHelper(getContext());
                SQLiteDatabase sd = db.getWritableDatabase();
                int userId = 0;
                Cursor cursor = sd.query("user", new String[]{"userId"}, "state=?", new String[]{"1"}, null, null, null);
                while (cursor.moveToNext()) {
                    userId = cursor.getInt(0);
                }
                cursor.close();
                final int finalUserId = userId;
                new Thread() {
                    public void run() {
                        try {
                            HttpUtils hu = new HttpUtils();
                            String data2;
                            final String src = getResources().getString(R.string.src_mysql) + "pswv/api/keysAcion/listAllUser";
                            final Map<String, String> map1 = new HashMap<String, String>();
                            map1.put("userId", finalUserId + "");
                            data2 = hu.submitPostData(src, map1, "utf-8");
                            JSONObject jsonObj = new JSONObject(data2);
                            int result = Integer.parseInt(jsonObj.getString("code"));
                            JSONArray jsonArray = jsonObj.getJSONArray("response");
                            if (result == 0) {
                                Message msg = Message.obtain();
                                msg.what = SUCCESS;
                                msg.obj = jsonArray;
                                mHandler.sendMessage(msg);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Message msg = Message.obtain();
                            msg.what = ERROR;
                            mHandler.sendMessage(msg);
                        }
                    }
                }.start();
            }
            break;
            case R.id.display_all_share: {
                new Thread() {
                    public void run() {
                        try {
                            HttpUtils hu = new HttpUtils();
                            String data2;
                            final String src = getResources().getString(R.string.src_mysql) + "pswv/api/shareKWordAction/listAll";
                            data2 = hu.submitPostData(src, "utf-8");
                            JSONObject jsonObj = new JSONObject(data2);
                            int result = Integer.parseInt(jsonObj.getString("code"));
                            JSONObject jsonObj1=jsonObj.getJSONObject("response");
                            JSONArray jsonArray = jsonObj1.getJSONArray("list");
                            if (result == 0) {
                                Message msg = Message.obtain();
                                msg.what = SHARE_SUCCESS;
                                msg.obj = jsonArray;
                                mHandler.sendMessage(msg);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Message msg = Message.obtain();
                            msg.what = ERROR;
                            mHandler.sendMessage(msg);
                        }
                    }
                }.start();
            }
            break;
            case R.id.kword_search: {
                DBHelper db = new DBHelper(getContext());
                SQLiteDatabase sd = db.getWritableDatabase();
                int userId = 0;
                Cursor cursor = sd.query("user", new String[]{"userId"}, "state=?", new String[]{"1"}, null, null, null);
                while (cursor.moveToNext()) {
                    userId = cursor.getInt(0);
                }
                cursor.close();
                final int finalUserId = userId;
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            HttpUtils hu = new HttpUtils();
                            String data2;
                            final String src = getResources().getString(R.string.src_mysql) + "pswv/api/keysAcion/searchUser";
                            final Map<String, String> map1 = new HashMap<String, String>();
                            String kwordsearch = text_search.getText().toString().trim();
                            map1.put("kwords", kwordsearch);
                            map1.put("userId", finalUserId + "");
                            data2 = hu.submitPostData(src, map1, "utf-8");
                            JSONObject jsonObj = new JSONObject(data2);
                            JSONObject jsonObj1 = jsonObj.getJSONObject("response");
                            JSONArray jsonArray = jsonObj1.getJSONArray("list");
                            int result = Integer.parseInt(jsonObj.getString("code"));
                            if (result == 0) {
                                Message msg = Message.obtain();
                                msg.obj = jsonArray;
                                msg.what = KWORDSEARCH_SUCCESS;
                                mHandler.sendMessage(msg);
                            } else {
                                Message msg = Message.obtain();
                                msg.what = NO_ADD;
                                mHandler.sendMessage(msg);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Message msg = Message.obtain();
                            msg.what = ERROR;
                            mHandler.sendMessage(msg);
                        }
                    }
                }.start();
            }
            break;
            case R.id.kword_search_share: {

                DBHelper db = new DBHelper(getContext());
                SQLiteDatabase sd = db.getWritableDatabase();
                int userId = 0;
                Cursor cursor = sd.query("user", new String[]{"userId"}, "state=?", new String[]{"1"}, null, null, null);
                while (cursor.moveToNext()) {
                    userId = cursor.getInt(0);
                }
                cursor.close();
                final int finalUserId = userId;
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            HttpUtils hu = new HttpUtils();
                            String data2;
                            final String src = getResources().getString(R.string.src_mysql) + "pswv/api/shareKWordAction/search";
                            final Map<String, String> map1 = new HashMap<String, String>();
                            String kwordsearch = text_search.getText().toString().trim();
                            map1.put("kwords", kwordsearch);
                            map1.put("userId", finalUserId + "");
                            data2 = hu.submitPostData(src, map1, "utf-8");
                            JSONObject jsonObj = new JSONObject(data2);
                            JSONObject jsonObj1 = jsonObj.getJSONObject("response");
                            JSONArray jsonArray = jsonObj1.getJSONArray("list");
                            int result = Integer.parseInt(jsonObj.getString("code"));
                            if (result == 0) {
                                Message msg = Message.obtain();
                                msg.obj = jsonArray;
                                msg.what = SHARESEARCH_SUCCESS;
                                mHandler.sendMessage(msg);
                            } else {
                                Message msg = Message.obtain();
                                msg.what = NO_ADD;
                                mHandler.sendMessage(msg);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            Message msg = Message.obtain();
                            msg.what = ERROR;
                            mHandler.sendMessage(msg);
                        }
                    }
                }.start();
            }
            break;
            default:
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int i, KeyEvent keyEvent) {
                if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && i == KeyEvent.KEYCODE_BACK) {
                    Button my_page = (Button) getActivity().findViewById(R.id.my_page);
                    Button kword_page = (Button) getActivity().findViewById(R.id.kword_page);
                    Button risk_page = (Button) getActivity().findViewById(R.id.risk_page);
                    Button need_page = (Button) getActivity().findViewById(R.id.need_page);
                    my_page.setVisibility(getView().VISIBLE);
                    kword_page.setVisibility(getView().VISIBLE);
                    risk_page.setVisibility(getView().VISIBLE);
                    need_page.setVisibility(getView().VISIBLE);
                    my_page.setBackground(getView().getContext().getResources().getDrawable(R.drawable.ditu1));
                    kword_page.setBackground(getView().getContext().getResources().getDrawable(R.drawable.ditu1));
                    risk_page.setBackground(getView().getContext().getResources().getDrawable(R.drawable.ditu1));
                    need_page.setBackground(getView().getContext().getResources().getDrawable(R.drawable.ditu1));
                    getFragmentManager()
                            .beginTransaction()
                            .addToBackStack(null)
                            .replace(R.id.realtabcontent, new Home()).commit();
                    return true;
                }
                return false;
            }
        });
    }

}
